package com.yuexiang.melodyhub.authserver.handler;

import com.yuexiang.melodyhub.authserver.feign.UserFeignService;
import com.yuexiang.melodyhub.authserver.handler.context.RegisterContext;
import com.yuexiang.melodyhub.common.constant.UsualConstant.BizCodeConstant;
import com.yuexiang.melodyhub.common.constant.UsualConstant.BizConstant;
import com.yuexiang.melodyhub.common.dto.user.UserAdd.param.UserAddParam;
import com.yuexiang.melodyhub.common.exception.RequestArgumentException;
import com.yuexiang.melodyhub.common.exception.gateway.UnavailableServiceException;
import com.yuexiang.melodyhub.common.handler.AbstractValidationHandler;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Component
public class CodeValidationHandler extends AbstractValidationHandler<RegisterContext> {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private UserFeignService userFeignService;

    @Override
    public void handler(RegisterContext content) {
        String redisCode = redisTemplate.opsForValue().get(BizConstant.EMAIL_CODE_CACHE_PREFIX + content.getOAuthRegisterParam().getEmail());
        if (!StringUtils.hasLength(redisCode) || !redisCode.replace("\"", "").split("_")[0].equals(content.getOAuthRegisterParam().getCode()))
            throw new RequestArgumentException(BizCodeConstant.Msg.CODE_IS_INVALID);

        try {
            UserAddParam userAddParam = new UserAddParam();
            BeanUtils.copyProperties(content.getOAuthRegisterParam(), userAddParam);
            userFeignService.add(userAddParam);
        } catch (Exception e) {
            throw new UnavailableServiceException();
        }
    }
}
